package com.fortune.common.spring.jackson.deserializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fortune.constants.Constants;

public class DateDeserializer extends JsonDeserializer<Date> {
	private Logger logger = LoggerFactory.getLogger(DateDeserializer.class);

	@Override
	public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		JsonToken t = p.getCurrentToken();
		if (t!=JsonToken.VALUE_STRING) {
			return null;
		}
		String value = p.getText().trim();
		if(value==null) {
			return null;
		}else {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_DAY);
				Date date = sdf.parse(value);
				return date;
			} catch (Exception e) {
				logger.error("date类型反序列化失败",e);
				return null;
			}
		}
//		else if (value.length()==Constants.DATE_FORMAT_DAY.length()) {
//			try {
//				SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_DAY);
//				Date date = sdf.parse(value);
//				return date;
//			} catch (Exception e) {
//				logger.error("date类型反序列化失败",e);
//				return null;
//			}
//		}
//		else {
//			try {
//				SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_SECOND);
//				Date date = sdf.parse(value);
//				return date;
//			} catch (Exception e) {
//				logger.error("date类型反序列化失败",e);
//				return null;
//			}
//		}
	}

	@Override
	public Class<?> handledType() {
		return Date.class;
	}

}
